package ua.org.nuos.sdms.clientgui.client.view.tabs;

import com.vaadin.data.Validator;
import com.vaadin.ui.*;
import ua.org.nuos.sdms.clientgui.client.components.PasswordForm;
import ua.org.nuos.sdms.clientgui.client.components.factory.ButtonFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.FormFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.LayoutFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.SeparatorFactory;
import ua.org.nuos.sdms.clientgui.client.components.fieldFactory.UserFieldFactory;
import ua.org.nuos.sdms.clientgui.client.components.tabs.DataTab;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.RemoveUserEvent;
import ua.org.nuos.sdms.clientgui.client.events.UpdateUserEvent;
import ua.org.nuos.sdms.clientgui.client.events.UpdateUserPasswordEvent;
import ua.org.nuos.sdms.clientgui.client.events.UserChangedEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.UserChangedListener;
import ua.org.nuos.sdms.clientgui.client.model.EntityBeanItem;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.User;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 18.03.12
 * Time: 19:07
 * To change this template use File | Settings | File Templates.
 */
public class UserConfigTab extends DataTab implements UserChangedListener {

    public static final String ID = "UserConfigTab";
    public static final String CONTENT_WIDTH = "550";
    private static final String caption = "Профиль пользователя";

    private EntityBeanItem<User> userBeanItem, passwordBeanItem;
    private Form userForm, passwordForm;

    public UserConfigTab() {
        super(caption);
        init();
    }

    private void init() {
        AppProxy.getInstance().getComponentLocator().addTab(ID, this);

        User user = AppProxy.getInstance().getServiceLocator().getAuthenticationBean().getCurrentUser();
        userBeanItem = new EntityBeanItem<User>(user);
        passwordBeanItem = new EntityBeanItem<User>(user);

        userForm = FormFactory.getForm(new UserFieldFactory(), userBeanItem, new String[]{"firstName", "lastName", "email"});
        passwordForm = new PasswordForm();
        FormFactory.initForm(passwordForm, new UserFieldFactory(), userBeanItem, new String[]{"password"});

        initComponents();
    }

    private void initComponents() {
        Button saveUser = ButtonFactory.getButton("Сохранить", getSaveUserConfigClickListener());
        ButtonFactory.setButtonColorStyle(saveUser, ButtonFactory.Color.GREEN);
        Button cancelUserChanges = ButtonFactory.getButton("Очистить", getCancelClickListener(userForm, userBeanItem));
        Layout userButtons = LayoutFactory.getHLayout(saveUser, cancelUserChanges);

        Button savePassword = ButtonFactory.getButton("Сохранить", getSavePasswordConfigClickListener());
        ButtonFactory.setButtonColorStyle(savePassword, ButtonFactory.Color.GREEN);
        Button cancelPasswordChanges = ButtonFactory.getButton("Очистить", getCancelClickListener(passwordForm, passwordBeanItem));
        Layout passwordButtons = LayoutFactory.getHLayout(savePassword, cancelPasswordChanges);

        Button removeUser = ButtonFactory.getButton("Удалить профиль", GlobalBoard.ID, RemoveUserEvent.class);
        ButtonFactory.setButtonColorStyle(removeUser, ButtonFactory.Color.RED);
        Label removeMessage = new Label("<b>Удаление профиля безвозвратно уничтожит все Ваши данные. " +
                "Одумайтесь, пока не позно.</b>", Label.CONTENT_XHTML);

        VerticalLayout userLayout = new VerticalLayout();
        userLayout.addComponent(new Label("<h2>Персональные данные:</h2>", Label.CONTENT_XHTML));
        userLayout.addComponent(userForm);
        userLayout.addComponent(userButtons);
        userLayout.setComponentAlignment(userButtons, Alignment.BOTTOM_RIGHT);

        VerticalLayout passwordLayout = new VerticalLayout();
        passwordLayout.addComponent(new Label("<h2>Смена пароля:</h2>", Label.CONTENT_XHTML));
        passwordLayout.addComponent(passwordForm);
        passwordLayout.addComponent(passwordButtons);
        passwordLayout.setComponentAlignment(passwordButtons, Alignment.BOTTOM_RIGHT);

        HorizontalLayout removeLayout = new HorizontalLayout();
        removeLayout.setWidth("100%");
        removeLayout.setSpacing(true);
        removeLayout.addComponent(removeMessage);
        removeLayout.addComponent(removeUser);
        removeLayout.setExpandRatio(removeMessage, 1.f);
        removeLayout.setComponentAlignment(removeUser, Alignment.BOTTOM_RIGHT);

        VerticalLayout content = new VerticalLayout();
        content.setWidth(CONTENT_WIDTH);
        content.setSpacing(true);
        content.addComponent(userLayout);
        content.addComponent(SeparatorFactory.getHorizontal());
        content.addComponent(passwordLayout);
        content.addComponent(SeparatorFactory.getHorizontal());
        content.addComponent(removeLayout);

        setDataContainer(content);
    }

    @Override
    public void userChanged(UserChangedEvent event) {
        User user = AppProxy.getInstance().getServiceLocator().getAuthenticationBean().getCurrentUser();
        if (user == null) {
            userBeanItem.setBean(new User());
            passwordBeanItem.setBean(new User());
        }
    }

    private Button.ClickListener getSaveUserConfigClickListener() {
        return new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    userForm.commit();
                    User user = userBeanItem.getBean();
                    AppProxy.getInstance().getController(GlobalBoard.ID).fire(new UpdateUserEvent(user));
                } catch (Validator.InvalidValueException e) {
                    Logger.getAnonymousLogger().log(Level.WARNING, "validation exception", e);
                }
            }
        };
    }

    private Button.ClickListener getCancelClickListener(final Form form, final EntityBeanItem<User> beanItem) {
        return new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                User user = AppProxy.getInstance().getServiceLocator().getAuthenticationBean().getCurrentUser();
                beanItem.setBean(user);
                form.discard();
            }
        };
    }

    private Button.ClickListener getSavePasswordConfigClickListener() {
        return new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    passwordForm.commit();
                    User user = passwordBeanItem.getBean();
                    AppProxy.getInstance().getController(GlobalBoard.ID).fire(new UpdateUserPasswordEvent(user.getPassword()));
                } catch (Validator.InvalidValueException e) {
                    Logger.getAnonymousLogger().log(Level.WARNING, "validation exception", e);
                }
            }
        };
    }
}
